<template>
<!--  特色场景管理-->
  <div class="permission">
    <div class="operate">
      <div>
        <div style="flex: 0 0 auto">
          <ep-search
            v-model="queryParam.k0402"
            :size="size"
            style="margin-left: 10px"
            placeholder="请输入场景名称"
            enter-button="chaxun "
            @search="
              () => {
                this.listQuery();
              }
            "
          ></ep-search>
        </div>
        <ep-button
          style="margin-left: 10px"
          icon="refresh.svg"
          :size="size"
          @click="
            () => {
              this.flushPage();
            }
          "
        ></ep-button>
        <ep-button
            style="margin-left: 15px"
            :size="size"
            icon="add.svg"
            @click="
            () => {
              this.addDevPlan();
            }
          "
        >新增
        </ep-button>
        <ep-button
            :size="size"
            style="margin-left: 15px"
            type="danger"
            icon="del.svg"
            @click="
            () => {
              this.delCharScene();
            }
          "
        >
          删除
        </ep-button>
      </div>

      <div>
      <column-manage  :column.sync="tableColumn" @change="columnChange"></column-manage>
        <ep-button
          style="margin-left: 10px"
          :size="size"
          icon="export.svg"
          @click="
            () => {
              this.exportExcel();
            }
          "
          >导出</ep-button
        >
      </div>
    </div>

    <div style="margin-top: 10px"></div>

    <a-modal
      :title="aModalTitle"
      centered
      style="top: 20px"
      width="65%"
      destroyOnClose
      :mask-closable="false"
      v-model="allotVisible"
    >
      <character-scene-manager-form ref="characterSceneManagerForm"/>
      <template slot="footer">
        <ep-button @click="allotHandleCancel">关闭</ep-button>
        <ep-button @click="allotHandleOk" type="save" v-if="showSave">保存</ep-button>
      </template>
    </a-modal>

    <div class="ep-table">
      <zh-table
        ref="devPlanList"
        rowId="roleId"
        height="auto"
        :url = "tableUrl"
        :columns="tableColumn"
        :data = "tableData"
        @checkbox-change="selectChangeEvent"
        @checkbox-all="selectAllEvent"
        :filter-config="{ remote: true }"
        @filter-change="filterChange"
      >
        <template #filter="{ $panel, column }">
          <input
            type="type"
            v-for="(option, index) in column.filters"
            :key="index"
            v-model="option.data"
            @input="$panel.changeOption($event, true, option)"
          />
        </template>
        <template #operate="{ row }">
          <ep-button size="small" type="rank" @click="allotTask(row)"
          >查看</ep-button>
          <ep-button size="small" type="rank" @click="editDevPlan(row)" style="margin-left: 5px;"
          >编辑</ep-button>
        </template>
      </zh-table>
    </div>
  </div>
</template>

<script>
import modal from "ant-design-vue/es/modal";
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
import {
  getCharSceneList,
  charSceneForSave,
  charSceneForUpdate,
  charSceneForDelete,
} from "@/services/system/whdngxlApi";
import { getBatchDict } from "@/services/system/api";
import characterSceneManagerForm from "@/pages/whdn/characterScene/form/characterSceneManagerForm";
import { TreeSelect } from "ant-design-vue";
import EpButton from "@/components/assembly/button";
import ZhTable from "@/components/zh-table/ZhTable";
import ColumnManage from "@/components/assembly/columnManage";
export default {
  name: "devPlanManager",
  components: {
    ColumnManage,
    EpButton,
    characterSceneManagerForm,
    ZhTable,
  },
  data() {
    return {
      aModalTitle: '',
      size: 'default',
      dictData: {
        b0104: [],
      },
      filtersData: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      // 分页参数
      tablePage: {
        total: 0,
        currentPage: 1,
        pageNum: 1,
        pageSize: 200,
      },
      tableUrl: getCharSceneList,
      tableColumn: [
        { type: "checkbox", width: 50, fixed: "left", visible: true },
        {
          type: "seq",
          width: 80,
          fixed: "left",
          align: "center",
          title: "序号",
          visible: true,
        },
        {
          field: "k0402",
          title: "场景名称",
          align: "center",
          visible: true,
        },
        {
          field: "k0403",
          title: "建设进度",
          align: "center",
          visible: true,
        },
        {
          field: "k0409",
          title: "场景评价",
          align: "center",
          visible: true,
        },
        // {
        //   field: "k0405",
        //   title: "访问量",
        //   align: "center",
        //   visible: true,
        // },
        {
          field: "operate",
          title: "操作",
          fixed: "right",
          align: "center",
          width: 250,
          slots: {
            // 使用插槽模板渲染
            default: "operate",
          },
          visible: true,
        },
      ],
      rules: {},
      tableData: [],
      visible: false,
      allotVisible: false,
      //表头
      toolbarConfig: {
        custom: true,
        slots: {},
      },
      queryParam: {
        k0402: "",
      },
      selectedRowKeys: [] /*table选中keys*/,
      selectionRows: [] /*table选中records*/,
      row: {},
      SHOW_PARENT,
      selectRuleBuild: {},
      orderRuleBuild: {},
      //查询规则
      selectRule: {
        k0402: {
          data: null,
          values: [],
          fuzzyQuery: true,
          multiple: false,
          targetField: "k0402",
        },
      },
      //排序规则
      orderRule: {
      },
      showSave: true
    };
  },
  mounted() {},
  created() {
    // 数据初始化
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    init() {
      this.listQuery();
    },
    addDevPlan(){
      this.showSave = true
      this.aModalTitle = '特色场景管理>新增'
      this.allotShowOrHide()
    },
    editDevPlan(row){
      this.showSave = true
      this.aModalTitle = '特色场景管理>编辑'
      this.allotShowOrHide()
      this.$nextTick(() => {
        this.$refs.characterSceneManagerForm.init(row)
      })
    },
    allotHandleOk() {
      this.$loading.show("正在处理数据,请等待...");
      debugger
      if(this.aModalTitle === '特色场景管理>新增'){
        this.$http.post(charSceneForSave, this.$refs.characterSceneManagerForm.getData()).then((res) => {
          this.$message.success("新增成功");
          this.allotShowOrHide()
          this.listQuery()
        }).finally(()=>{
          this.$loading.hide();
        });
      }else if(this.aModalTitle === '特色场景管理>编辑'){
        this.$http.post(charSceneForUpdate, this.$refs.characterSceneManagerForm.getData()).then((res) => {
          this.$message.success("编辑成功");
          this.allotShowOrHide()
          this.listQuery()
        }).finally(()=>{
          this.$loading.hide();
        });
      }

    },
    allotHandleCancel() {
      this.allotVisible = false;
    },
    allotShowOrHide() {
      this.allotVisible = !this.allotVisible;
    },
    listQuery() {
      //手动清空用户的选择
      this.$refs.devPlanList.clearCheckboxRow();
      //手动清空用户保留选中的行数据
      this.$refs.devPlanList.clearCheckboxReserve();
      //删除所选中的数据
      this.$refs.devPlanList.removeCheckboxRow();
      this.selectionRows = [];
      this.selectedRowKeys = [];
      this.$refs.devPlanList.isAllChecked = false;
      this.row = {};
      this.tableData = [];
      this.createQuery();
      this.$refs.devPlanList.query(this.queryParam);
    },
    createQuery(){
      this.selectRuleBuild = JSON.parse(JSON.stringify(this.selectRule));
      const filterVOList = [];
      Object.keys(this.queryParam).forEach((key) => {
        const fieldRule = this.selectRuleBuild[key];
        if (fieldRule && this.queryParam[key]) {
          if (fieldRule.multiple) {
            fieldRule.values = this.queryParam[key].split(',');
          } else {
            fieldRule.data = this.queryParam[key];
          }
        }
      });
      Object.keys(this.selectRuleBuild).forEach((key) => {
        if (this.selectRuleBuild[key].data) {
          filterVOList.push({
            property: this.selectRuleBuild[key].targetField,
            data: this.selectRuleBuild[key].data,
            fuzzyQuery: this.selectRuleBuild[key].fuzzyQuery,
          });
        } else if (this.selectRuleBuild[key].values.length > 0) {
          filterVOList.push({
            property: this.selectRuleBuild[key].targetField,
            values: this.selectRuleBuild[key].values,
          });
        }
      });
      const orderVOList = [];
      Object.keys(this.orderRuleBuild).forEach((key) => {
        if (this.orderRuleBuild[key].order) {
          orderVOList.push({
            property: this.orderRuleBuild[key].targetField,
            order: this.orderRuleBuild[key].order,
          });
        }
      })
      this.queryParam.filterVOList = filterVOList;
      this.queryParam.orderVOList = orderVOList;
      this.queryParam.pageNum = this.tablePage.currentPage;
      this.queryParam.pageSize = this.tablePage.pageSize;
    },
    //刷新
    flushPage() {
      this.queryParam.k0402 = "";
      this.init();
    },
    exportExcel() {
      this.$refs.devPlanList.exportData("特色场景管理",'csv')

    },
    //获取勾选的数据
    getRecords() {
      if (this.$refs.devPlanList.isAllChecked) {
        this.selectionRows=this.$refs.devPlanList.getCheckboxRecords()
      } else {
        this.selectionRows = this.$refs.devPlanList.getAllCheckboxRecords();
      }
      if (this.selectionRows.length === 0) {
        modal.warn({ title: "提示", content: "请先进行勾选再操作" });
        return;
      }
      console.log(this.selectionRows)
      return this.selectionRows
    },
    delCharScene(){
      this.$http.post(charSceneForDelete,{k0401List: this.getRecords().map((item)=>{
          return item.k0401
        })}).then((res) => {
        this.$message.success("删除成功");
        this.listQuery()
      });
    },
    allotTask(row) {
      this.showSave = false
      this.aModalTitle = '特色场景管理>查看'
      this.allotShowOrHide()
      this.$nextTick(() => {
        this.$refs.characterSceneManagerForm.init(row,true)
      })
    },
    columnChange() {
      this.$refs.devPlanList.refreshColumn();
    },
    //复选框事件(保留翻页选中的数据)
    selectChangeEvent({ checked, records, reserves, row }) {
      // console.log(checked ? '勾选事件' : '取消事件')
      // console.log('当前选中的数据：' + records)
      // console.log('翻页时其他页的数据：' + reserves)
      // console.log('当前选中的数据行：' + row )
      //勾选选中时
      if (checked) {
        //第一次选数据，还未进行翻页时
        if (reserves.length == 0) {
          this.selectedRowKeys = records.map((v) => v.b0101);
          this.selectionRows = records;
        } else {
          //b0101集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectedRowKeys = [
            ...reserves.map((v) => v.b0101),
            ...records.map((v) => v.b0101),
          ];
          //数据集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectionRows = [...reserves, ...records];
        }
      } else {
        //取消选中时
        let b0101Index = this.selectedRowKeys.indexOf(row.b0101);
        if (b0101Index > -1) {
          //删除取消选中删除指定元素b0101
          this.$delete(this.selectedRowKeys, b0101Index);
        }

        let dataIndex = null;
        for (let i = 0; i < this.selectionRows.length; i++) {
          if (this.selectionRows[i].b0101 == row.b0101) {
            dataIndex = i;
            break;
          }
        }
        //删除取消选中的元素整个对象
        this.$delete(this.selectionRows, dataIndex);
      }
    },
    //vxe复选框当前页全选中方法(保留翻页选中的数据)：
    selectAllEvent({ checked, records, reserves }) {
      // console.log(checked ? '勾选事件' : '取消事件')
      // console.log('当前选中的数据：' + records)
      // console.log('翻页时其他页的数据：' + reserves)
      //全选中时
      if (checked) {
        //第一次选数据，还未进行翻页时
        if (reserves.length == 0) {
          this.selectedRowKeys = records.map((v) => v.b0101);
          this.selectionRows = records;
        } else {
          //b0101集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectedRowKeys = [
            ...reserves.map((v) => v.b0101),
            ...records.map((v) => v.b0101),
          ];
          //数据集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectionRows = [...reserves, ...records];
        }
      } else {
        //取消全选时,直接将翻页数据赋值，当前页数据不用加上
        this.selectionRows = reserves;
        this.selectedRowKeys = reserves.map((v) => v.b0101);
      }
    },

    getFiltersData(that, tableName) {
      //把拿到的字典遍历进筛选的数组中
      let keyArr = Object.keys(that.dictData);
      for (let i = 0; i < keyArr.length; i++) {
        let filterKey = keyArr[i];
        let filterParam = that.dictData[filterKey];
        let filterObj = [];
        for (let j = 0; j < filterParam.length; j++) {
          let filterArr = {
            label: filterParam[j].dictValue,
            value: filterParam[j].dictValue,
            data: filterParam[j].dictKey
          };
          filterObj.push(filterArr);
        }
        that.filtersData[filterKey] = filterObj;
        that.$refs[tableName].setFilter(
          [filterKey] + "Name",
          that.filtersData[filterKey]
        );
      }
    },

    //筛选
    filterChange({ column, property, values, datas, filterList, $event }) {
      console.log(column);
      console.log(property);
      console.log(values);
      console.log(datas);
      console.log(filterList);
      console.log($event);
      if(values.length === 0){
        this.queryParam[property] = ''
      }
      filterList.forEach((item) => {
        if(this.selectRule[item.field].multiple){
          this.queryParam[item.field] = item.datas.join(',')
        }else {
          this.queryParam[item.field] = item.datas[0]
        }
      });
      this.listQuery()
    },
  },
};
</script>

<style lang="less" scoped>
.permission {
  //padding: 15px 20px 0;
  height: 100%;

  .desc,
  .operate {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #fff;

    > div {
      flex: 0 0 auto;
      display: flex;
      align-items: center;
    }


  }

  .desc {
    margin-bottom: 20px;
  }

  .operate {
    margin-bottom: 15px;
    .field {
      flex: 0 0 auto;
      position: relative;
      margin-left: 15px;
      .field-box {
        position: absolute;
        top: 40px;
        left: 0;
        right: -40px;
        z-index: 99;
        border: 1px solid #2175a9;
        background: #002a44;
        border-radius: 5px;
        ul {
          padding: 10px;
          li {
            padding: 1px 0;
          }
        }
        .btn {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 5px;
          border-top: 1px solid #2175a9;
          color: #fff;
          p {
            flex: 1;
            text-align: center;
            cursor: pointer;
            &:hover {
              color: #49bbeb;
            }
          }
        }
      }
    }
  }
  //.ep-table {
  //  height: calc(100% - 130px);
  //}
}

@media screen and (max-width: 1500px) {
  .ep-table {
    height: calc(100% - 96px);
  }
}

@media screen and (min-width: 1500px) {
  .ep-table {
    height: calc(100% - 110px);
  }
}
</style>
